# -*- coding: utf-8 -*-
import windnd
import tkinter as tk
from tkinter import scrolledtext, messagebox,Toplevel,PhotoImage,CENTER,Label,BOTH,ttk

from threading import Thread
import os
import time
from queue import Queue
from openpyxl import load_workbook, Workbook
import random
from datetime import datetime
from zsm import *

class ExcelMerger:
    @staticmethod
    def merge_files(file_paths, output_path, progress_queue, remove_duplicates):
        """合并多个Excel文件到指定输出路径"""
        try:
            if not file_paths:
                progress_queue.put(("error", "没有选择任何文件！"))
                return

            # 收集所有文件中出现过的sheet名称
            all_sheet_names = set()
            for file_path in file_paths:
                try:
                    wb = load_workbook(file_path, read_only=True)
                    all_sheet_names.update(wb.sheetnames)
                    wb.close()
                except Exception as e:
                    progress_queue.put(("error", f"无法读取文件 {file_path}: {str(e)}"))
                    continue

            # 创建新工作簿
            output_wb = Workbook()
            output_wb.remove(output_wb.active)  # 删除默认创建的sheet

            # 合并每个sheet
            for sheet_name in all_sheet_names:
                merged_data = []
                for file_path in file_paths:
                    try:
                        wb = load_workbook(file_path, read_only=True)
                        if sheet_name not in wb.sheetnames:
                            progress_queue.put(("warning", f"文件 {os.path.basename(file_path)} 缺少工作表 {sheet_name}"))
                            continue

                        sheet = wb[sheet_name]
                        for row in sheet.iter_rows(values_only=True):
                            if not remove_duplicates or row not in merged_data:
                                merged_data.append(row)
                        wb.close()
                    except Exception as e:
                        progress_queue.put(("error", f"处理文件 {file_path} 失败: {str(e)}"))
                        continue

                # 写入到新sheet
                output_ws = output_wb.create_sheet(sheet_name)
                for row_idx, row_data in enumerate(merged_data, 1):
                    output_ws.append(row_data)
                progress_queue.put(("progress", f"工作表 {sheet_name} 合并完成"))

            output_wb.save(output_path)
            progress_queue.put(("success", f"所有文件已成功合并到 {output_path}"))

        except Exception as e:
            progress_queue.put(("error", f"合并过程中发生未知错误: {str(e)}"))


class ExcelMergeGUI:
    def __init__(self, root):
        self.root = root
        self.file_list = []
        self.progress_queue = Queue()
        self.running = False
        self.remove_duplicates = tk.BooleanVar()

        # 初始化界面
        self.setup_ui()
        # 绑定拖放事件
        windnd.hook_dropfiles(self.root, func=self.handle_dropped_files)
        # 启动队列检查
        self.check_queue()

    def setup_ui(self):
        """初始化用户界面"""
        self.root.title("xlsx文件批量合并工具     by: 风二西 2025.02.25")
        self.root.geometry('480x200+200+100')

        # 日志输出区域
        log_frame = tk.LabelFrame(self.root, text="操作日志")
        log_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=4)

        self.log_text = scrolledtext.ScrolledText(log_frame, height=10, bg="#FAFAD2")
        self.log_text.pack(fill=tk.BOTH, expand=True)

        # 底部栏
        bottom_frame = ttk.Frame(self.root)
        bottom_frame.pack(side=tk.BOTTOM,fill=tk.X, padx=5, pady=1)


        #去重复复选框
        self.chk_remove_duplicates = ttk.Checkbutton(bottom_frame, text="去重复", variable=self.remove_duplicates)
        self.chk_remove_duplicates.pack(side=tk.LEFT, padx=2)

        ttk.Button(bottom_frame, text="赞赏作者",
                   command=self.donate_author).pack(side=tk.LEFT)
        ttk.Label(bottom_frame,
                  text="更多工具、教程，欢迎关注bilibili风二西").pack(side=tk.RIGHT)


    def donate_author(self):
        self.zsm_windows = Toplevel(self.root)
        # 替换窗口浮于上方
        self.zsm_windows.wm_attributes("-topmost", 1)
        self.zsm_windows.title('赞赏作者')
        self.photo1 = PhotoImage(data=zsm123)
        self.zsm1 = Label(self.zsm_windows, image=self.photo1,
                          compound=CENTER)
        self.zsm1.pack(fill=BOTH, expand=True)

    def handle_dropped_files(self, files):
        """处理拖放文件"""
        valid_files = []
        for path in files:
            file_path = path.decode('gbk')
            if file_path.lower().endswith('.xlsx'):
                valid_files.append(file_path)
                self.log(f"[添加文件] {file_path}")
        if valid_files:
            self.file_list.extend(valid_files)
            self.start_merge()

    def start_merge(self):
        """启动合并线程"""
        if not self.file_list:
            messagebox.showwarning("警告", "请先添加要合并的文件！")
            return

        # 生成随机文件名
        random_num = random.randint(1, 10000)
        output_dir = os.path.dirname(self.file_list[0])
        output_file = os.path.join(output_dir, f"merged_{random_num}.xlsx")

        # 禁用复选框防止重复操作
        self.chk_remove_duplicates.config(state=tk.DISABLED)
        self.running = True

        # 启动合并线程
        Thread(target=self.run_merge_task, args=(output_file,), daemon=True).start()

    def run_merge_task(self, output_path):
        """执行合并任务的线程方法"""
        ExcelMerger.merge_files(self.file_list, output_path, self.progress_queue, self.remove_duplicates.get())
        self.progress_queue.put(("done",))

    def check_queue(self):
        """定期检查进度队列"""
        while not self.progress_queue.empty():
            msg_type, *content = self.progress_queue.get()
            if msg_type == "progress":
                self.log(f"[进度] {content[0]}")
            elif msg_type == "warning":
                self.log(f"[警告] {content[0]}", "orange")
            elif msg_type == "error":
                self.log(f"[错误] {content[0]}", "red")
            elif msg_type == "success":
                self.log(f"[成功] {content[0]}", "green4")
                messagebox.showinfo("完成", content[0])
            elif msg_type == "done":
                self.running = False
                self.chk_remove_duplicates.config(state=tk.NORMAL)
                self.file_list = []

        self.root.after(100, self.check_queue)

    def log(self, message, color="black"):
        """添加日志信息"""
        # 获取当前时间
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # 在日志信息前加上时间
        message_with_time = f"[{current_time}] {message}"
        self.log_text.configure(state=tk.NORMAL)
        self.log_text.insert(tk.END, message_with_time + "\n", color)
        self.log_text.configure(state=tk.DISABLED)
        self.log_text.see(tk.END)


if __name__ == "__main__":
    root = tk.Tk()
    app = ExcelMergeGUI(root)
    root.mainloop()